<template>
  <div>
    <span>
      更新时间:
      <el-date-picker v-model="time" type="daterange" range-separator="至" start-placeholder="开始" end-placeholder="结束"
        size="default" />
    </span>
    <span v-for="(item, index) in infoArray" :key="index">
      {{ item.label }}:
      <el-select v-model="queryParam[item.value]" class="m-2" placeholder="请选择">
        <el-option v-for="item in infolist[item.value]" :key="item.value" :label="item.text" :value="item.value" />
      </el-select>
    </span>
    <el-button type="primary" @click="queryList()">查询</el-button>
    <el-button type="primary" @click="showDialog()">新增</el-button>
    <el-table :data="tableData" border style="width: 100%">
      <template v-for="(item, index) in columnList">
        <el-table-column :key="index" :prop="item.field" :label="item.title" :width="item.width">
          <template slot-scope="scope">
            <span> {{ scope.row[item.field] | qxSelffilter(item.value) }}</span>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="操作">
      <template slot-scope="{row,$index}">
        <el-button @click="updateShowDialog(row)" type="primary" >
          修改
        </el-button>
        <el-button  type="danger" @click="deleteUser(row)" >
          删除
        </el-button>
      </template>
    </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 20px; text-align: center" :current-page="queryParam.currentPage"
      :page-size="queryParam.pageSize" :page-sizes="[3, 5, 10, 20]" :total="total" :pager-count="5"
      @size-change="handleSizeChange" @current-change="goPage" layout=" prev, pager, next , total,sizes" />
    <!-- 弹框
      :visible.sync:控制对话框显示与隐藏用的
      Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可
     -->
    <el-dialog :visible.sync="dialogFormVisible" :title="dialogName">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>
        <!-- 下拉选项
          item:  { label: "用户状态", value: "status", enumType: "status" },
          obj: {"enumType":"status","value":"0","text":"启用"}
         -->
        <span v-for="(item, index) in infoArray" :key="index">
          <el-form-item :label="item.label" :prop="item.value">
            <el-select v-model="form[item.value]" class="m-2" placeholder="请选择">
              <el-option v-for="obj in infolist[item.value]" 
              :key="obj.value" 
              :label="obj.text" 
              :value="item.String ? obj.value : Number(obj.value)" />
            </el-select>
          </el-form-item>
        </span>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { EnumUtility } from "@/utils/EnumUtility";
import * as DateUtil from "@/utils/DateUtil";
export default {
  name: "user_info",
  mounted() {
    // this.queryList()
  },
  created() {
    // 给枚举赋值
    let enumUtility = new EnumUtility();
    this.infoArray.forEach((element) => {
      if (element.enumType) {
        //枚举数据结构 [{"enumType":"status","value":"0","text":"启用"},{"enumType":"status","value":"1","text":"禁用"}]
        console.log('element.enumType=',element.enumType)
        console.log('enumUtility.Get(element.enumType)',enumUtility.Get(element.enumType))
        this.infolist[element.value] = enumUtility.Get(element.enumType);
      }
    });
  },
  data() {
    let _startTime = DateUtil.ToString(
      DateUtil.AddDays(new Date(), -7),
      "yyyy-MM-dd"
    );
    let _endTime = DateUtil.ToString(new Date(), "yyyy-MM-dd");
    //自定义校验规则
    var validateUserName = (rule, value, callback) => {
      //自定义校验规则
      if (value.length < 6 || value.length > 10) {
        callback(new Error("登录账号6-10位"));
      } else {
        callback();
      }
    };
    return {
      // 时间选择器
      time: [_startTime, _endTime],
      // 下拉选择属性
      infoArray: [
        /*
         * label:下拉选项的标题,如:用户状态
         * value: 选择值列表 与 传到 服务端的字段: 如:status=30
         * enumType:从字典=>枚举 中的下拉选项映射值 , 枚举值赋值是在创建vue对象后,即方法中实现的
         */
        { label: "用户状态", value: "status", enumType: "status" },
        { label: "用户类型", value: "type", enumType: "user_type" },
      ],
      // 下拉选项值
      /* 枚举中完成赋值的status,type*/
      infolist: {},
      // 列表查询参数
      queryParam: {
        currentPage: 1,
        pageSize: 10,
        startTime: _startTime,
        endTime: DateUtil.ToString(
          DateUtil.AddDays(_endTime, +1),
          "yyyy-MM-dd"
        ),
      },
      // 列表数据
      tableData: [],
      total: 0,
      // 列字段
      columnList: [
        { title: "编号", field: "id" },
        { title: "账号", field: "userName" },
        { title: "类型", field: "type", value: { enum: "user_type" } },
        { title: "状态", field: "status", value: { enum: "status" } },
        { title: "备注", field: "remark" },
        {
          title: "更新时间",
          field: "updateTime",
          value: { date: "MM-dd hh:mm:ss" },
        },
        {
          title: "创建时间",
          field: "createTime",
          value: { date: "MM-dd hh:mm:ss" },
        },
      ],
      dialogFormVisible: false, // 是否显示弹框
      dialogName: '', // 弹框标题 如:新增用户 或 修改 用户
      form: {  // 新增 或 修改表单数据
      },
      rules: {
        // 品牌名称的验证规则
        // require:必须要校验字段（前面五角星有关系）  message 提示信息    trigger:用户行为设置（事件的设置:blur、change）
        // tmName 对应表单上的prop的名称必须一致  <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
        userName: [
          { required: true, message: '必须输入登录账号', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
          //自定义校验规则
          { validator: validateUserName, trigger: "change" },
        ],
        password: [{ required: true, message: "请输入密码" }],
        status: [{ required: true, message: "请选择状态" }],
        type: [{ required: true, message: "请选择类型" }],
      }
    };
  },
  watch: {
    time(val) {
      if (!val) {
        // 参数为空时清空数据
        this.queryParam.startTime = "";
        this.queryParam.endTime = "";
      }
      if (val && val.length > 0) {
        this.queryParam.startTime = DateUtil.ToString(val[0], "yyyy-MM-dd");
        this.queryParam.endTime = DateUtil.ToString(
          DateUtil.AddDays(val[1], +1),
          "yyyy-MM-dd"
        );
      }
    },
  },
  methods: {
    async queryList() {
      const result = await this.$api.user.queryList(this.queryParam);
      if (result.code == "100") {
        this.tableData = result.data.list;
        this.total = result.data.total;
      }
    },
    goPage(currentPage) {
      this.queryParam.currentPage = currentPage;
      this.queryList();
    },
    handleSizeChange(pageSize) {
      this.queryParam.pageSize = pageSize;
      this.queryParam.currentPage = 1;
      this.queryList();
    },
    showDialog() {
      // console.log('显示弹框')
      this.dialogName = "添加用户"
      this.form = {}
      this.dialogFormVisible = true
    },
    updateShowDialog(row) {
      this.dialogName="修改用户"
      this.form = { ...row };
      //显示对话框
      this.dialogFormVisible = true;
    },
    submitForm() {
      //当全部验证字段通过，再去书写业务逻辑
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          let result = await this.$api.user.updateOrSave(this.form)
          if (result.code == '100') {
            // 关闭窗口
            this.dialogFormVisible = false
            // 查询数据
            this.queryList()
          }
        } else {
          console.log("检查提交参数");
          return false;
        }
      });
    },
    deleteUser(row){
        //弹框
        this.$confirm(`你确定删除:${row.userName}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //当用户点击确定按钮的时候会出发
          //向服务器发请求
          let result = await this.$api.user.deleteUser(row.id);
          //如果删除成功
          if (result.code == '100') {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //再次获取品牌列表数据
            this.queryList()
          }
        })
        .catch(() => {
          //当用户点击取消按钮的时候会触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
  },
};
</script>
  
<style lang="scss"></style>
  